<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>发布创意</title>
    <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">

    <!--标准mui.css-->
    <link rel="stylesheet" href="${base!}/assets/front/h5/css/mui.min.css" />
    <link rel="stylesheet" href="${base!}/assets/front/h5/css/hryc.css" />
    <link rel="stylesheet" href="${base!}/assets/front/newH5/css/index.css?v=${@date.getDateTime()}" />
    <!--App自定义的css-->
    <!--<link rel="stylesheet" type="text/css" href="../css/app.css"/>-->
    <style>
        .mui-table-view .mui-media-object {
            line-height: 42px;
            max-width: 145px;
            height: 100px;
        }
        .jiage-text{
            font-size: 18px;
            color: red;
            margin-right:10px ;
        }
        [v-cloak]{
            display: none !important;
        }
        .mui-input-group:before,.mui-input-row:after,.mui-input-group:after{
            display: none;
        }
    </style>
</head>
<body>


<header class="mui-bar mui-bar-nav top-color">
    <a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left" style="color: white;"></a>
    <h1 class="mui-title" style="color: white;">
        发布创意
    </h1>
</header>

<div  style="padding: 60px 20px 40px 20px;background: #ffffff" id="vue">
    <form class="mui-input-group">
        <div class="mui-input-row">
            <input style="border: 1px solid rgba(0, 0, 0, .2);" v-model="title"  type="text" placeholder="请输入标题">
        </div>
    </form>
    <div class="mui-input-row" style="margin: 10px 0;">
        <textarea id="textarea" v-model="content" rows="5" placeholder="请输入内容"></textarea>
    </div>
    <div>
        <input type="file" id="choose" accept="image/*" multiple>
        <ul class="img-list"></ul>
        <a id="upload">上传图片</a>
        <span class="tips">只允许上传jpg、png及gif</span>
        <div class="pic-list" style="display: none;">
            你上传的图片(图片有效期为1分钟)：
        </div>
    </div>
    <div style="width: 300px;margin: 0 auto;">
        <button type="button" v-on:click="add" class="mui-btn mui-btn-primary mui-btn-block">发布</button>
    </div>
</div>




<script type="text/javascript" src="${base!}/assets/front/h5/js/mui.js" ></script>
<script type="text/javascript" src="${base!}/assets/front/h5/js/vue.js" ></script>
<script type="text/javascript" src="${base!}/assets/front/h5/js/jquery-2.0.0.min.js" ></script>
<script type="text/javascript" src="${base!}/assets/decorate/pc/decoratecommon/js/layer/mobile/layer.js" ></script>
<script type="application/javascript">
    mui.init({
        swipeBack:true //启用右滑关闭功能
    });

    var _picUrl = "";

    var vue = new Vue({
        el: '#vue',
        data: {
            title: '',
            content:''
        },
        created:function () {   //实例初始化创建完成执行

            // this.getvideoList()     //调用自身方法

        },
        methods:{              //定义封装方法
            //保存收货地址
            add:function () {
                var self = this;

                var imageUrlStrs = getImageUrlStrs();

                if(self.title == ''){
                    layerAlert("请填写标题");
                    return;
                }

                if(self.content == ''){
                    layerAlert("请填写内容");
                    return;
                }

                if(imageUrlStrs == ""){
                    layerAlert("至少上传一张图片")
                    return;
                }



                $.ajax({
                    type:"POST",
                    url:"${base!}/open/h5/show/addShow.html",
                    dataType:"JSON",
                    data:{
                        title:self.title,
                        content:self.content,
                        imageUrlStrs:imageUrlStrs,
                        picUrl: _picUrl
                    },
                    success:function(data){
                        if (data.code == 0) {
                            window.location.href='${base!}/open/h5/niantu/talentShow.html';
                        } else {

                        }
                    }
                });

            }
        },
        watch:{     //监听器
            // carModel:function () {
            //     this.getProvince();
            // }
        }

    })

    function getImageUrlStrs() {
        var url = "";
        var i = 0;
        $(".imageUrlList").each(function(){
            i++;
            var s = $(this).html();
            if(i==1){
                url = s;
                _picUrl = s;
            }else {
                url = url+","+s
            }

        });
        return url;
    }

    function layerAlert(msg) {
        //提示
        layer.open({
            content: msg
            ,skin: 'msg'
            ,time: 2 //2秒后自动关闭
        });
    }

</script>
<script>
    var filechooser = document.getElementById("choose");
    //    用于压缩图片的canvas
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext('2d');
    //    瓦片canvas
    var tCanvas = document.createElement("canvas");
    var tctx = tCanvas.getContext("2d");
    var maxsize = 100 * 1024;
    $("#upload").on("click", function() {
        filechooser.click();
    })
        .on("touchstart", function() {
            $(this).addClass("touch")
        })
        .on("touchend", function() {
            $(this).removeClass("touch")
        });
    filechooser.onchange = function() {
        if (!this.files.length) return;
        var files = Array.prototype.slice.call(this.files);
        if (files.length > 9) {
            alert("最多同时只可上传9张图片");
            return;
        }
        files.forEach(function(file, i) {
            if (!/\/(?:jpeg|png|gif)/i.test(file.type)) return;
            var reader = new FileReader();
            var li = document.createElement("li");
//          获取图片大小
            var size = file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + "MB" : ~~(file.size / 1024) + "KB";
            li.innerHTML = '<div class="progress"><span></span></div><div class="size">' + size + '</div>';
            $(".img-list").append($(li));
            reader.onload = function() {
                var result = this.result;
                var img = new Image();
                img.src = result;
                $(li).css("background-image", "url(" + result + ")");
                //如果图片大小小于100kb，则直接上传
                if (result.length <= maxsize) {
                    img = null;
                    upload(result, file.type, $(li));
                    return;
                }
//      图片加载完毕之后进行压缩，然后上传
                if (img.complete) {
                    callback();
                } else {
                    img.onload = callback;
                }
                function callback() {
                    var data = compress(img);
                    upload(data, file.type, $(li));
                    img = null;
                }
            };
            reader.readAsDataURL(file);
        })
    };
    //    使用canvas对大图片进行压缩
    function compress(img) {
        var initSize = img.src.length;
        var width = img.width;
        var height = img.height;
        //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
        var ratio;
        if ((ratio = width * height / 4000000) > 1) {
            ratio = Math.sqrt(ratio);
            width /= ratio;
            height /= ratio;
        } else {
            ratio = 1;
        }
        canvas.width = width;
        canvas.height = height;
//        铺底色
        ctx.fillStyle = "#fff";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        //如果图片像素大于100万则使用瓦片绘制
        var count;
        if ((count = width * height / 1000000) > 1) {
            count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
//            计算每块瓦片的宽和高
            var nw = ~~(width / count);
            var nh = ~~(height / count);
            tCanvas.width = nw;
            tCanvas.height = nh;
            for (var i = 0; i < count; i++) {
                for (var j = 0; j < count; j++) {
                    tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
                    ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
                }
            }
        } else {
            ctx.drawImage(img, 0, 0, width, height);
        }
        //进行最小压缩
        var ndata = canvas.toDataURL('image/jpg', 0.1);
        console.log('压缩前：' + initSize);
        console.log('压缩后：' + ndata.length);
        console.log('压缩率：' + ~~(100 * (initSize - ndata.length) / initSize) + "%");
        tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
        return ndata;
    }
    //    图片上传，将base64的图片转成二进制对象，塞进formdata上传
    function upload(basestr, type, $li) {
        var text = window.atob(basestr.split(",")[1]);
        var buffer = new Uint8Array(text.length);
        var pecent = 0, loop = null;
        for (var i = 0; i < text.length; i++) {
            buffer[i] = text.charCodeAt(i);
        }
        var blob = getBlob([buffer], type);
        var xhr = new XMLHttpRequest();
        var formdata = getFormData();
        formdata.append('Filedata', blob);
        formdata.append('type', 'wap');
        xhr.open('post', '${base!}/open/file/upload/image');
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var jsonData = JSON.parse(xhr.responseText);
                var imagedata = jsonData;
                var text = "";
                if(imagedata.code==0){
                    text = '上传成功';
                } else{
                    text = '上传失败';
                }
                console.log(text + '：' + imagedata.path);
                clearInterval(loop);
                //当收到该消息时上传完毕
                $li.find(".progress span").animate({'width': "100%"}, pecent < 95 ? 200 : 0, function() {
                    $(this).html(text);
                });
                if (!imagedata.data) return;
                $(".pic-list").append('<p class="imageUrlList">'+imagedata.data+'</p>');
            }
        };
        //数据发送进度，前50%展示该进度
        xhr.upload.addEventListener('progress', function(e) {
            if (loop) return;
            pecent = ~~(100 * e.loaded / e.total) / 2;
            $li.find(".progress span").css('width', pecent + "%");
            if (pecent == 50) {
                mockProgress();
            }
        }, false);
        //数据后50%用模拟进度
        function mockProgress() {
            if (loop) return;
            loop = setInterval(function() {
                pecent++;
                $li.find(".progress span").css('width', pecent + "%");
                if (pecent == 99) {
                    clearInterval(loop);
                }
            }, 100)
        }
        xhr.send(formdata);
    }
    /**
     * 获取blob对象的兼容性写法
     * @param buffer
     * @param format
     * @returns {*}
     */
    function getBlob(buffer, format) {
        try {
            return new Blob(buffer, {type: format});
        } catch (e) {
            var bb = new (window.BlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder);
            buffer.forEach(function(buf) {
                bb.append(buf);
            });
            return bb.getBlob(format);
        }
    }
    /**
     * 获取formdata
     */
    function getFormData() {
        var isNeedShim = ~navigator.userAgent.indexOf('Android')
            && ~navigator.vendor.indexOf('Google')
            && !~navigator.userAgent.indexOf('Chrome')
            && navigator.userAgent.match(/AppleWebKit\/(\d+)/).pop() <= 534;
        return isNeedShim ? new FormDataShim() : new FormData()
    }
    /**
     * formdata 补丁, 给不支持formdata上传blob的android机打补丁
     * @constructor
     */
    function FormDataShim() {
        console.warn('using formdata shim');
        var o = this,
            parts = [],
            boundary = Array(21).join('-') + (+new Date() * (1e16 * Math.random())).toString(36),
            oldSend = XMLHttpRequest.prototype.send;
        this.append = function(name, value, filename) {
            parts.push('--' + boundary + '\r\nContent-Disposition: form-data; name="' + name + '"');
            if (value instanceof Blob) {
                parts.push('; filename="' + 'blob.jpg' + '"\r\nContent-Type: ' + value.type + '\r\n\r\n');
                parts.push(value);
            }
            else {
                parts.push('\r\n\r\n' + value);
            }
            parts.push('\r\n');
        };
        // Override XHR send()
        XMLHttpRequest.prototype.send = function(val) {
            var fr,
                data,
                oXHR = this;
            if (val === o) {
                // Append the final boundary string
                parts.push('--' + boundary + '--\r\n');
                // Create the blob
                data = getBlob(parts);
                // Set up and read the blob into an array to be sent
                fr = new FileReader();
                fr.onload = function() {
                    oldSend.call(oXHR, fr.result);
                };
                fr.onerror = function(err) {
                    throw err;
                };
                fr.readAsArrayBuffer(data);
                // Set the multipart content type and boudary
                this.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
                XMLHttpRequest.prototype.send = oldSend;
            }
            else {
                oldSend.call(this, val);
            }
        };
    }
</script>
</body>
</html>
